<template>
  <div class="add-target">
    <el-drawer size="90%" :visible.sync="drawerVisible" :append-to-body="true" :before-close="closeSelf" direction="btt">
      <span slot="title" style="display: flex; justify-content: space-between;">
        <span>{{form.id ? '编辑目标' : '添加目标'}}</span>
      </span>
      <div class="content" :style="{ 'height': documentClientHeight*0.9 + 'px' }">
        <div class="form-wrapper">
          <el-form ref="form" label-width="140px" label-position="left">
            <div style="padding: 0 30px;">
              <el-form-item label="目标名称">
                <span style="color: red; position: absolute; left: -150px;">*</span>
                <el-input v-model="form.goalName" placeholder="请输入目标名称，不是描述工作职责，应该是提炼重要的目标" :disabled="!canEditGoal"></el-input>
              </el-form-item>
              <el-form-item label="目标周期">
                <span style="color: red; position: absolute; left: -150px;">*</span>
                <el-cascader v-model="formTime" :options="timeArr" @change="changeTime" separator="" :disabled="!canEditGoal" style="width: 100%;"></el-cascader>
              </el-form-item>
              <el-form-item label="目标类型">
                <span style="color: red; position: absolute; left: -150px;">*</span>
                <el-radio-group v-model="form.goalTag" :disabled="!canEditGoal">
                  <el-radio :label="tag.index" v-for="tag in goalTag" :key="tag.index">{{tag.name}}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="执行部门">
                <span style="cursor: pointer; color: #409EFF;" v-if="!form.goalExecuteDepartmentId" @click="showOrganizationDialog">选择</span>
                <span style="cursor: pointer; color: #409EFF; position: relative;" v-else @click="showOrganizationDialog">{{form.goalExecuteDepartmentName}}
                  <i style="cursor: pointer;" class="el-icon-delete" v-if="canEditGoal" @click.stop="delOrganization"></i>
                </span>
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" :rows="4" v-model="form.goalContent" placeholder="请输入备注描述" :disabled="!canEditGoal"></el-input>
              </el-form-item>
              <el-form-item label="上级关键结果">
                <span style="cursor: pointer; color: #409EFF;" v-if="!form.goalBelongId" @click="showGoalsDialog">选择</span>
                <span style="cursor: pointer; color: #409EFF; position: relative;" v-else @click="showGoalsDialog">{{form.goalBelongName}}
                  <i style="cursor: pointer;" class="el-icon-delete" v-if="canEditGoal" @click.stop="delkr"></i>
                </span>
              </el-form-item>
              <el-form-item label="目标状态" v-if="form.id">
                <el-radio-group v-model="form.goalStatus" size="small" :disabled="!canEditGoal">
                  <el-radio-button label="1">拟定状态</el-radio-button>
                  <el-radio-button label="2">执行状态</el-radio-button>
                  <el-radio-button label="3">完成状态</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="bottom" style="height: 64px; line-height: 64px; border-top: 1px solid #E6E6E6; padding-left: 130px">
          <el-button type="primary" @click="submitForm()" size="mini">保存</el-button>
          <el-button plain @click="closeSelf()" size="mini">取消</el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog title="公司部门" :visible.sync="organizationDialogVisible" width="800px" :append-to-body="true">
      <div style="height: 300px; overflow: auto;" class="organization-wrapper">
        <organization ref="department" @curOrganization="getOrganization" />
      </div>
    </el-dialog>
    <el-dialog title="选择对齐的关键结果" :visible.sync="goalsDialogVisible" width="800px" :append-to-body="true">
      <div class="result-dialog">
        <div style="width: 180px;padding-right:20px;">
          <el-input placeholder="请输入筛选内容" prefix-icon="el-icon-search" v-model="searchData.name" @input="filterData" @clear="filterData" clearable></el-input>
          <div style="margin-top: 20px;">
            <div v-for="item in goalTag" :key="item.index" class="tags" :class="{'active': searchData.tag===item.index}" @click="selectTag(item.index)">{{item.name}}</div>
            <div class="tags" :class="{'active': searchData.tag===''}" @click="selectTag('')">全部</div>
          </div>
        </div>
        <div style="height: 500px; overflow: auto; flex: 1;">
          <goals ref="goals" :postSearchTime.sync="formTime" @chooseKr="getAlignKr" :curGoalId="form.id" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import formUtil from "@/utils/formUtil";
import organization from './component/organization'
import goals from './component/goals'

export default {
  data () {
    return {
      goalTag: [{index: '1', name: '公司级'},{index: '2', name: '部门级'},{index: '3', name: '团队级'}],
      form: {
        goalName: '',
        goalExecuteDepartmentId: '',
        goalExecuteDepartmentName: '',
        goalTag: '1',
        goalLevel: '1',
        goalBelongId: '',
        goalBelongName: '',
        goalContent: '',
        goalPeriodYear: '',
        goalPeriodTime: '',
        goalStatus: '1',
      },
      organizationDialogVisible: false,
      goalsDialogVisible: false,
      formTime: [],
      timeArr: [],
      goalBelongTag: 0,
      canDelGoal: true,
      searchData: {
        name: '',
        tag: ''
      }
    };
  },
  props: ["drawerVisible", "userAsd", "documentClientHeight", "postFormTime"],
  components: {
    organization, goals
  },
  computed: {
    canEditGoal() {
      return this.userAsd.userLevel === '1' || (this.userAsd.userLevel === '2' && this.form.hasGoalAuthority === '1' && this.form.id) || (this.userAsd.userLevel === '2' && !this.form.id)
    },
    getGoalStatus() {
      return this.userAsd.userDepartmentId.split(",").indexOf(this.form.goalExecuteDepartmentId) > -1
    }
  },
  mounted () {
    this.setTimeArr();
  },
  methods: {
    async init(id, krId, krName) {
      formUtil.resetData(this.form);
      formUtil.resetData(this.searchData);
      this.canDelGoal = true;
      if(this.$refs.goals) this.$refs.goals.searchGoalTag('');
      if(this.$refs.department) this.$refs.department.getOrganization();
      if(id) {
        this.form = await this.$httpN.postB('lkr/goal/info', {id: id});
        this.formTime = [`${this.form.goalPeriodYear}`, `${this.form.goalPeriodTime}`];
        this.form.krList.forEach(kr => {
          if(kr.canUpdateProgress !== '1') this.canDelGoal = false
        })
      } else {
        this.goalBelongTag = 0;
        this.form.goalLevel = '1';
        this.form.goalStatus = '1';
        this.form.goalTag = '1';
        //目标周期默认当前周期
        this.formTime = formUtil.deepCopy(this.postFormTime);
        this.form.goalPeriodYear = this.formTime[0]
        this.form.goalPeriodTime = this.formTime[1]
        if(krId) {
          let krInfo = await this.$httpN.postB('lkr/kr/krInfo', {id: krId})
          let goalInfo = await this.$httpN.postB('lkr/goal/info', {id: krInfo.krBelongGoalId})
          this.goalBelongTag = Number(goalInfo.goalTag);
          this.form.goalBelongId = krId
          this.form.goalBelongName = krName
        }
      }
    },
    closeSelf() {
      this.$emit("closeAddTarget");
    },
    getOrganization(data) {
      this.organizationDialogVisible = false;
      this.form.goalExecuteDepartmentId = data.id;
      this.form.goalExecuteDepartmentName = data.departmentName;
      this.getGoalStatus ? this.form.goalStatus = '2' : this.form.goalStatus = '1'
    },
    delOrganization() {
      this.form.goalExecuteDepartmentId = '';
      this.form.goalExecuteDepartmentName = '';
      this.form.goalStatus = '1'
    },
    getAlignKr(kr, goal) {
      this.goalBelongTag = Number(goal.goalTag);
      this.form.goalBelongId = kr.id;
      this.form.goalBelongName = kr.krName;
      this.goalsDialogVisible = false;
    },
    delkr() {
      this.goalBelongTag = Number(this.form.goalTag);
      this.form.goalBelongId = '';
      this.form.goalBelongName = '';
    },
    async submitForm() {
      if(!this.canEditGoal) return this.$message.error('您没有操作权限');
      if(!this.form.goalName) return this.$message.error('请输入目标名称');
      this.form.goalPeriodYear = this.formTime[0]
      this.form.goalPeriodTime = this.formTime[1]
      if(!this.form.goalPeriodYear || !this.form.goalPeriodTime) return this.$message.error('请选择目标周期');
      if(!this.form.goalTag) return this.$message.error('请选择目标类型');
      if(this.form.goalTag * 1 < this.goalBelongTag) return this.$message.error('目标类型不可超过上级目标类型');

      if (!await this.$httpN.postB(this.form.id ? 'lkr/goal/goalUpdate' : 'lkr/goal/goalSave', this.form)) return
      formUtil.submitSuccess('保存成功');
      this.closeSelf();
      this.$emit('reload');
    },
    changeTime(data) {
      this.form.goalPeriodYear = data[1].substr(0,4);
      this.form.goalPeriodTime = data[1].substr(4,4);
    },
    setTimeArr() {
      let year = parseInt((new Date).Format(`yyyy`));
      this.timeArr = []
      for (let i=-5; i<=5; i++) {
        this.timeArr.push({
          value: `${year-i}`,
          label: `${year-i}年`,
          children: [{
            value: `0201`,
            label: '第1季度LKR'
          },{
            value: `0202`,
            label: '第2季度LKR'
          },{
            value: `0203`,
            label: '第3季度LKR'
          },{
            value: `0204`,
            label: '第4季度LKR'
          },{
            value: `0200`,
            label: '年度LKR'
          }]
        })
      }
    },
    async delGoal() {
      formUtil.submitConfirm('您确定要删除目标吗', async ()=> {
        if(!await this.$httpN.postB('lkr/goal/goalDelete',{id: this.form.id})) return;
        formUtil.submitSuccess('删除成功');
        this.closeSelf();
        this.$emit('reload');
      })
    },
    showOrganizationDialog() {
      if(this.canEditGoal) this.organizationDialogVisible = true;
    },
    showGoalsDialog() {
      if(this.canEditGoal) {
        this.goalsDialogVisible = true
        this.$nextTick(() => {
          this.$refs.goals.getGoalList(true)
        })
      }
    },
    selectTag(tag) {
      this.searchData.tag = tag;
      this.searchData.name = '';
      this.$refs.goals.searchGoalTag(tag)
    },
    filterData() {
      this.$refs.goals.searchGoalOrKrName(this.searchData.name)
    }
  }
}
</script>

<style lang='scss' scoped>
.add-target {
  height: 100%;
}
.content {
  background-color: #F7F7F7;
  .form-wrapper {
    width: 650px;
    height: calc(100% - 64px);
    padding-top: 20px;
    margin: 0 40px;
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 0;
      height: 0;
    }
  }
}
.result-dialog {
  display: flex;
  .tags {
    width: 100%;
    height: 36px;
    line-height: 36px;
    padding: 0 20px;
    cursor:pointer;
  }
  .active {
    background-color: #E8EEF6;
    color: #3296FA;
  }
}
.organization-wrapper::-webkit-scrollbar {/*滚动条整体样式*/
  width: 4px;     /*高宽分别对应横竖滚动条的尺寸*/
  height: 4px;
  scrollbar-arrow-color:red;
}
.organization-wrapper::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 5px #DEDEDE;
  background: rgba(0,0,0,0.2);
  scrollbar-arrow-color:red;
}
.organization-wrapper::-webkit-scrollbar-track {/*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px #F5F5F5;
  border-radius: 0;
  background: rgba(0,0,0,0.1);
}
</style>